import { URL } from '@/api/config'
import axios from 'axios'
import { ElMessage } from "element-plus";
import router from "@/router";
import pinia from '@/store/store'
import { Token } from '@/store'


const service = axios.create({
    baseURL: URL,
    timeout: 6000
})

service.interceptors.request.use(
     config =>{
         const storeToken = Token(pinia)
         let token = storeToken.token
         if (token) {
             config.headers['Authorization'] = `${token}`
         }else {
             token = localStorage.getItem('token')
             if (token){
                 config.headers['Authorization'] = `${token}`
             }else {
                 router.push('/login')
             }

         }
         return config
    },
    error =>{
        ElMessage.error(error)
        return Promise.reject(error)
    }
)

service.interceptors.response.use(response => {
        const { code, message} = response.data
        if (code === 0) {
            return response.data
        } else {
            ElMessage.error(message)
            if (message === '身份认证失败!'){
                router.push('/login')
            }
            return Promise.reject(new Error(message))
        }
    },
    error => {
        router.push('/login')
        ElMessage.error(error.message)
        return Promise.reject(error)
    })

export default service
